package com.project.springboot.enumparam;

import com.google.common.collect.Maps;
import com.project.springboot.exception.ResponseException;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.convert.converter.Converter;

import java.util.Arrays;
import java.util.Map;
import java.util.Optional;

/**
 * description: 枚举转换器
 * @author 朱正磊
 * @date 2024-01-18 13:38:19
 */
public class IdCodeToEnumConverter<T extends IdCodeBaseEnum> implements Converter<String, T> {

    private final Map<String, T> idEnumMap = Maps.newHashMap();

    private final Map<String, T> codeEnumMap = Maps.newHashMap();

    public IdCodeToEnumConverter(Class<T> enumType) {
        Arrays.stream(enumType.getEnumConstants())
                .forEach(e -> {
                    idEnumMap.put(e.getId().toString(), e);
                    codeEnumMap.put(e.getCode(), e);
                });
    }

    /**
     * description: 将字符串类型的源对象转换成枚举对象
     * @author 朱正磊
     * @date 2024-01-18 13:39:46
     * @param source 源对象，不能为空
     * @return 返回枚举对象
     */
    @Override
    public T convert(@NotNull String source) {
        return Optional.of(source)
                .map(idEnumMap::get)
                .orElseGet(() -> Optional.of(source)
                        .map(codeEnumMap::get)
                        .orElseThrow(() -> new ResponseException("参数和枚举不匹配！")));
    }

}
